<?php
/**
 * Token模块
 * 
 * @author ShuangYa
 * @package EasyAccount
 * @category Model
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2017 ShuangYa
 * @license https://www.sylibs.com/go/easyaccount/license
 */
namespace ea\model;

use yesf\library\ModelAbstract;
use ea\library\Cache;

class CompanionToken extends ModelAbstract {
	protected static $_table_name = 'token';
	protected static $_primary_key = 'id';
}
class Token {
	use CompanionTrait;
	/**
	 * 验证token是否有效
	 * 若有效，则返回token信息，无效则返回FALSE
	 * @access public
	 * @return boolean/string
	 */
	public static function verify($token, $tverify) {
		//如果存在token，则校验token是否有效
		$token = self::get($token);
		if ($token['verify'] === $tverify) {
			return $token;
		} else {
			return FALSE;
		}
	}
	/**
	 * 生成新的token
	 * @access public
	 * @param string $uid
	 * @param int $expire_day token有效期，默认为14天
	 * @return string
	 */
	public static function add($uid, $expire_day = 14) {
		$token = substr(md5(uniqid($uid, TRUE)), 0, 12);
		$tverify = substr(md5(uniqid($uid, TRUE)), 0, 18);
		$expire = date('Y-m-d H:i:s', time() + 3600 * 24 * $expire_day);
		$insert = [
			'id' => $token,
			'verify' => $tverify,
			'uid' => $uid,
			'expire' => $expire
		];
		self::getCompanion()->add($insert);
		Cache::set('token_' . $token, swoole_serialize($insert), 1200); //缓存20分钟
		return [$token, $tverify];
	}
	/**
	 * 获取token
	 * 若验证通过，则返回token信息，否则返回NULL
	 * @access public
	 * @param string $token
	 * @return array
	 */
	public static function get(string $token) {
		if (Cache::exists('token_' . $token)) {
			$rs = swoole_unserialize(Cache::get('token_' . $token));
		} else {
			$rs = self::getCompanion()->get($token);
		}
		if (!$rs['verify']) {
			return NULL;
		}
		if (strtotime($rs['expire']) <= time()) {
			//token过期
			self::del($token);
			return NULL;
		}
		Cache::set('token_' . $token, swoole_serialize($rs), 1200); //缓存20分钟
		return $rs;
	}
	/**
	 * 移除token
	 * @access public
	 * @param string $token
	 */
	public static function del(string $token) {
		self::getCompanion()->del($token);
		Cache::del('token_' . $token);
	}
	/**
	 * 移除用户现有的全部token
	 * @access public
	 * @param int $id
	 */
	public static function delUser(int $id) {
		$list = self::getCompanion()->list(['uid' => $id]);
		foreach ($list as $v) {
			Cache::del('token_' . $v['id']);
		}
		self::getCompanion()->del(['uid' => $id]);
	}
}